package com.gd.util;

import java.text.MessageFormat;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;

import com.gd.controller.TestSocketController;

public class CustomConfigurator extends Configurator {

	HttpSession httpSession;

	// modifyHandshake() is called before getEndpointInstance()!
	@Override
	public <T> T getEndpointInstance(Class<T> clazz)
			throws InstantiationException {
		// TODO Auto-generated method stub
		T endpoint = super.getEndpointInstance(clazz);

		if (endpoint instanceof TestSocketController) {
			((TestSocketController) endpoint).setHttpSession(httpSession); // <--
																			// The
																			// injection
																			// point
		} else {
			throw new InstantiationException(MessageFormat.format(
					"Expected instanceof \"{0}\". Got instanceof \"{1}\".",
					TestSocketController.class, endpoint.getClass()));
		}
		return endpoint;
	}

	@Override
	public void modifyHandshake(ServerEndpointConfig sec,
			HandshakeRequest request, HandshakeResponse response) {
		// TODO Auto-generated method stub

		httpSession = (HttpSession) request.getHttpSession();
		super.modifyHandshake(sec, request, response);
	}

}
